import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Select,
  Button,
  Menu, Dropdown, Icon,
  Divider, message, Modal,
} from 'antd';
import StandardTable from '@/components/StandardTable';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import UpdateForm from './createFrom';
import DescView from './descView';
import SelectRole from './selectRole';
import styles from '../UserManage.less';
import { powerBtnFunc } from '@/utils/utils';

const Option = Select.Option;
const FormItem = Form.Item;

@connect(({ userModels, loading }) => ({
  userModels,
  loading: loading.models.userModels,
}))

@Form.create()
class UserManage extends PureComponent {

  constructor(props) {
    super(props);
    this.state = {
      modalVisible: false,
      updateModalVisible: false,
      lookDescView: false,
      SelectRoleView: false,
      selectedRows: {},
      formValues: {},
      pagination: {
        pageNo: 1,
        pageSize: 15,
      },
    };
  }


  onChange(record) {

    const { dispatch } = this.props;
    const { pagination } = this.state;
    dispatch({
      type: 'userModels/status',
      payload: {
        adminNo: record.adminNo,
        status: record.status === 1 ? 2 : 1,
      },
      callback: (res) => {
        if (res.code === 200) {
          message.success('修改成功');
          dispatch({
            type: 'userModels/fetch',
            payload: pagination,
          });
        } else {
          message.error(res.errMsg);
        }
      },
    });
  }

  columns = [
    {
      title: '用户编码',
      dataIndex: 'adminNo',
      key: 'adminNo',
    },
    {
      title: '账号',
      dataIndex: 'account',
      key: 'account',
    },
    {
      title: '真实姓名',
      dataIndex: 'realName',
      key: 'realName',
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      key: 'email',
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
    },
    {
      title: '性别',
      dataIndex: 'gender',
      key: 'gender',
      render: val => <span>{val === 1 ? '女' : '男'}</span>,

    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: val => <span>{val === 1 ? '启用' : '停用'}</span>,
    },
    {
      title: '操作',
      key: 'dataIndex',
      render: (text, record) => {
        const menu = (
          <Menu>
            {
              powerBtnFunc('100023', [
                <Menu.Item key={'1'}>
                  <a onClick={() => this.handleBindRole(true, record)}>绑定角色</a>
                </Menu.Item>,
              ])
            }
            {
              powerBtnFunc('100005', <Menu.Item key={'2'}>
                  <a onClick={() => this.handleMenuClick(record)}>删除</a>
                </Menu.Item>,
              )
            }

          </Menu>
        );
        return (
          <Fragment>
            {
              powerBtnFunc(
                '100002',
                [<a key={'1'} onClick={() => this.handleUpdateModalVisible(true, record)}>修改</a>,
                  <Divider key={'2'} type="vertical"/>],
              )
            }
            {powerBtnFunc('100006', [
              <a key={'1'} onClick={() => this.onChange(record)}>{record.status === 1 ? '停用' : '启用'}</a>,
              <Divider key={'2'} type="vertical"/>,
            ])
            }
            <Dropdown overlay={menu}>
              <a className="ant-dropdown-link" href="#">
                更多 <Icon type="down"/>
              </a>
            </Dropdown>
          </Fragment>
        );
      },
    },
  ];


  componentDidMount() {
    const { dispatch } = this.props;
    const { pagination } = this.state;
    dispatch({
      type: 'userModels/getDept',
      payload: {
        status: 1,
      },
    });
    //请求用户列表
    dispatch({
      type: 'userModels/fetch',
      payload: pagination,
    });
  }

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;

    this.setState({
      pagination: {
        pageNo: pagination.current,
        pageSize: 15,
      },
    });
    const params = {
      pageNo: pagination.current,
      pageSize: 15,
      ...formValues,
    };
    dispatch({
      type: 'userModels/fetch',
      payload: params,
    });
  };
  //重置
  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    this.setState({
      formValues: {},
    });
    dispatch({
      type: 'userModels/fetch',
      payload: {},
    });
  };


  handleMenuClick = e => {
    const { dispatch } = this.props;
    const { pagination } = this.state;
    Modal.confirm({
      title: '确认',
      content: '确定删除该用户吗？',
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        dispatch({
          type: 'userModels/remove',
          payload: {
            key: e.adminNo,
          },
          callback: (res) => {
            if (res.code === 200) {
              message.success('操作成功');
              dispatch({
                type: 'userModels/fetch',
                payload: pagination,
              });
            } else {
              message.error(res.errMsg);
            }
          },
        });
      },
    });

  };

  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };
  //搜索
  handleSearch = e => {
    e.preventDefault();

    const { dispatch, form } = this.props;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      const values = {
        ...fieldsValue,
      };
      this.setState({
        formValues: values,
      });

      dispatch({
        type: 'userModels/fetch',
        payload: values,
      });
    });
  };
  //新建显示窗口
  handleModalVisible = flag => {
    this.setState({
      modalVisible: !!flag,
      updateModalVisible: !!flag,
      selectedRows: {},
    });
  };
  //修改
  handleUpdateModalVisible = (flag, record) => {
    this.setState({
      updateModalVisible: !!flag,
      modalVisible: !flag,
      selectedRows: record,
      formVals: record,
    }, () => {
      if (!!flag) {
        const { dispatch } = this.props;
        dispatch({
          type: 'userModels/getUserDesc',
          payload: { adminNo: record.adminNo },
        });
      }
    });
  };
  //查看
  handleLookDesc = (flag, record) => {
    this.setState({
      lookDescView: !!flag,
      selectedRows: record,
    }, () => {
      if (!!flag) {
        const { dispatch } = this.props;
        dispatch({
          type: 'userModels/getUserDesc',
          payload: { adminNo: record.adminNo },
        });
      }
    });
  };

  handleBindRole = (flag, record) => {
    this.setState({
      SelectRoleView: !!flag,
      selectedRows: record,
    });
  };


  handleSelectRoles = (flag, record) => {
    const { pagination } = this.state;
    this.setState({
      SelectRoleView: !!flag,
    }, () => {
      let arr = [];
      record.map((item) => {
        arr.push(item.roleNo);
      });
      if (!flag && arr.length > 0) {
        const { dispatch } = this.props;
        const { selectedRows } = this.state;
        dispatch({
          type: 'userModels/bindRole',
          payload: { roleNos: arr, adminNo: selectedRows.adminNo },
          callback(res) {
            if (res.code === 200) {
              message.success('绑定成功');
              dispatch({
                type: 'userModels/fetch',
                payload: pagination,
              });
            }
          },
        });
      }
    });
  };
  // 新建请求
  handleAdd = fields => {
    const { dispatch } = this.props;
    dispatch({
      type: 'userModels/add',
      payload: fields,
      callback: (response) => {
        this.handleModalVisible();
        dispatch({
          type: 'userModels/fetch',
        });
      },
    });

  };
  // 修改请求
  handleUpdate = fields => {
    const { pagination } = this.state;
    const { dispatch } = this.props;
    dispatch({
      type: 'userModels/update',
      payload: fields,
      callback: () => {
        dispatch({
          type: 'userModels/fetch',
          payload: pagination,
        });
        this.handleUpdateModalVisible(false, []);
      },
    });

  };

  renderSimpleForm() {
    const { form: { getFieldDecorator } } = this.props;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={6} sm={24}>
            <FormItem label="账号">
              {getFieldDecorator('account')(<Input placeholder="请输入"/>)}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
            <FormItem label="真实姓名">
              {getFieldDecorator('nickName')(<Input placeholder="请输入"/>)}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
            <FormItem label="性别">
              {getFieldDecorator('gender')(
                <Select placeholder="请选择" style={{ width: '100%' }}>
                  <Option key={'1'} value={1}>女</Option>
                  <Option key={'2'} value={2}>男</Option>
                  <Option key={''} value={''}>全部</Option>
                </Select>,
              )}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
        <span className={styles.submitButtons}>
        <Button type="primary" htmlType="submit">
        查询
        </Button>
        <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
        重置
        </Button>

        </span>
          </Col>
        </Row>
      </Form>
    );
  }


  render() {
    const { userModels: { data, deptList, userDesc }, loading } = this.props;
    const { selectedRows, modalVisible, updateModalVisible, lookDescView, SelectRoleView } = this.state;

    const parentMethods = {
      handleAdd: this.handleAdd,
      handleModalVisible: this.handleModalVisible,
      handleUpdateModalVisible: this.handleUpdateModalVisible,
      handleUpdate: this.handleUpdate,
    };

    return (
      <PageHeaderWrapper title="用户列表">
        <Card bordered={false}>

          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderSimpleForm()}</div>
            <div className={styles.tableListOperator}>
              {
                powerBtnFunc('100001',
                  <Button key={'1'} icon="plus" type="primary" onClick={() => this.handleModalVisible(true)}>
                    新建
                  </Button>)
              }
            </div>
            <StandardTable
              selectedRows={selectedRows}
              loading={loading}
              data={data ? data : []}
              rowKey={'adminNo'}
              rowSelectHide={true}
              columns={this.columns}
              onChange={this.handleStandardTableChange}
            />
          </div>
        </Card>
        <DescView
          handleLookDesc={this.handleLookDesc}
          selectedRows={userDesc ? userDesc : ''}
          lookDescView={lookDescView}/>

        <UpdateForm
          {...parentMethods}
          updateModalVisible={updateModalVisible}
          modalVisible={modalVisible}
          values={selectedRows}
          deptList={deptList ? deptList : []}
        />
        {
          SelectRoleView ?
            <SelectRole
              SelectRoleView={SelectRoleView}
              selectedRows={selectedRows}
              handleSelectRole={this.handleSelectRoles}
              handleBindRole={this.handleBindRole}
            /> : ''}


      </PageHeaderWrapper>
    );
  }
}

export default UserManage;
